//
//  BDHomeSearchResultViewController.m
//  BadBoy
//
//  Created by wen on 2017/4/7.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "BDHomeSearchResultViewController.h"
#import "BDHomeTableViewCell.h"
#import "BDHomeModel.h"
#import "PBViewController.h"
#import "BDUserInfoViewController.h"
#import "BDForwardViewController.h"
#import "BDHomeDetailViewController.h"
#import "PopoverView.h"
#import "BDUserModel.h"
#import "BDCityInfo.h"
#import <UMSocialCore/UMSocialCore.h>
#import <UShareUI/UShareUI.h>
#import "AppDelegate.h"
#import "BDVipPayView.h"
#import "BDVIPViewController.h"
#import "BDButtonAlert.h"

@interface BDHomeSearchResultViewController ()<UITableViewDelegate, UITableViewDataSource, PBViewControllerDelegate, PBViewControllerDataSource>
{
    NSInteger currentSelectedIndex;
    NSIndexPath *exchangeIndexPath;
    NSArray *showImagesArray;
    UIView *curClickView;
}
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *datasource;

@end

@implementation BDHomeSearchResultViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = ASLocalizedString(@"搜索结果");
    [self requestDatasource];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [self loginSuccessRefresh];
}

- (void)loginSuccessRefresh{
    [self.tableView reloadData];
}

- (void)requestDatasource{
    NSString *url = [NSString stringWithFormat:@"%@posts?page=%@&size=%@&type=5&keyword=%@", KBDBaseURL, self.startPage, self.pageSize, self.keyword];
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *headValid = [BDUserModel getHeaderValidation];
    
    NSString *lastCity = [[NSUserDefaults standardUserDefaults] objectForKey:@"lastCity"];
    BDCityInfo *cityInfo = [BDCityInfo getCityWithName:lastCity type:BDCityTypeCity];
    NSString *currentCityID = [NSString stringWithFormat:@"%@", @(cityInfo.infoID)];
    
    if ([currentCityID isNotEmpty]) {
        url = [url stringByAppendingString:[NSString stringWithFormat:@"&city_id=%@", currentCityID]];
    }
    
    url = [url stringByAppendingString:[NSString stringWithFormat:@"&category=%zd", [BDButtonAlert getTypeidWitTypeString:self.typeString]]];
    
    //获取帖子列表数据
    RACCommand *command = [BDNetworkingServer yy_GET:url parameters:nil validation:headValid automaticProcessingError:YES];
    RACSignal *signal = [command execute:nil];
    [signal subscribeNext:^(id  _Nullable x) {
        self.isEnd = [x[@"is_end"] boolValue];
        self.startPage = x[@"next_page"];
        NSMutableArray *array = [BDHomeModel mj_objectArrayWithKeyValuesArray:x[@"list"]];
        [self.datasource addObjectsFromArray:array];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        [self.tableView reloadData];
        [self setTableiewFooterViewStateFor:self.tableView datasourceCount:self.datasource.count];
    }];
    
    [signal subscribeError:^(NSError * _Nullable error) {
        // BDLog(ASLocalizedString(@"首页数据请求失败：%@"), error);
    }];

}

#pragma mark ------------------------tableView代理---------------------------
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.datasource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    BDHomeModel *model = self.datasource[indexPath.section];
    //    // BDLog(ASLocalizedString(@"文本高度:%.2f"), model.contentHeight);
    return model.cellHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 10;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    __block BDHomeModel *model = self.datasource[indexPath.section];
    BDHomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"homeResCell" forIndexPath:indexPath];
    [cell configeWithModel:model avatarBlock:^{
        BDUserInfoViewController *userVC = [[BDUserInfoViewController alloc] initWithUserID:model.user.user_id isFollow:model.is_follow guanzhuBlock:^(BOOL isFollow) {
            model.is_follow = isFollow;
        }];
        [self.navigationController pushViewController:userVC animated:YES];
    } allButtonBlock:^{
        model.isOpen = !model.isOpen;
        [self.tableView reloadData];
    } zanBlock:^(UIButton *button){
        // BDLog(ASLocalizedString(@"点赞按钮"));
        NSString *url = [NSString stringWithFormat:@"%@post/%@/praise", KBDBaseURL, @(model.my_id)];
        NSDictionary *para = @{@"id":@(model.my_id)};
        NSString *headValid = [BDUserModel getHeaderValidation];
        RACSignal *signal = [[BDNetworkingServer yy_POST:url parameters:para validation:headValid automaticProcessingError:YES] execute:nil];
        
        [signal subscribeNext:^(id  _Nullable x) {
            button.userInteractionEnabled = YES;
            button.selected = YES;
            model.praiseCount++;
            model.praise = YES;
            [self.tableView reloadData];
        }];
        [signal subscribeError:^(NSError * _Nullable error) {
            button.userInteractionEnabled = YES;
            [MBManager showBriefAlert:ASLocalizedString(@"点赞失败")clickHidden:NO clickBlock:nil];
        }];
    } forwardBlock:^{
        exchangeIndexPath = indexPath;
        BDForwardViewController *forwardVC = [[BDForwardViewController alloc] init];
        forwardVC.homeModel = model;
        forwardVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:forwardVC animated:YES];
    } pinglunBlock:^{
        exchangeIndexPath = indexPath;
        BDHomeDetailViewController *commntVC = [[BDHomeDetailViewController alloc] init];
        commntVC.homeModel = model;
        commntVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:commntVC animated:YES];
    } sharedBlock:^{
        // BDLog(ASLocalizedString(@"分享按钮"));
        [UMSocialUIManager setPreDefinePlatforms:@[@(UMSocialPlatformType_WechatSession),@(UMSocialPlatformType_WechatTimeLine),@(UMSocialPlatformType_WechatFavorite)]];
        [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
            // 根据获取的platformType确定所选平台进行下一步操作
            NSString *url = [NSString stringWithFormat:@"%@tool/shareData", KBDBaseURL];
            NSString *headValid = [BDUserModel getHeaderValidation];
            RACSignal *signal = [[BDNetworkingServer yy_GET:url parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
            
            [signal subscribeNext:^(id  _Nullable x) {
                //创建分享消息对象
                UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
                
                //创建网页内容对象
                NSString *thumbURL = x[@"share_logo"];
                NSString *title = x[@"share_title"];
                NSString *descr = x[@"share_text"];
                NSString *webUrl = x[@"share_url"];
                UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:title
                                                                                         descr:descr
                                                                                     thumImage:thumbURL];
                //设置网页地址
                shareObject.webpageUrl = webUrl;
                
                //分享消息对象设置分享内容对象
                messageObject.shareObject = shareObject;
                
                //调用分享接口
                [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
                    if (error) {
                        UMSocialLogInfo(@"************Share fail with error %@*********",error);
                    }else{
                        if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                            //                            UMSocialShareResponse *resp = data;
                            //                            //分享结果消息
                            //                            UMSocialLogInfo(@"response message is %@",resp.message);
                            //                            //第三方原始返回的数据
                            //                            UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
                            //                            NSLog(ASLocalizedString(@"分享成功了"));
                            NSString *backUrl = [NSString stringWithFormat:@"%@post/%@/shared", KBDBaseURL, @(model.my_id)];
                            RACSignal *backSignal = [[BDNetworkingServer yy_POST:backUrl parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
                            [backSignal subscribeNext:^(id  _Nullable x) {
                                model.sharedCount++;
                                [self.tableView reloadData];
                                [MBManager showBriefAlert:ASLocalizedString(@"分享成功")clickHidden:NO clickBlock:nil];
                            }];
                            [backSignal subscribeError:^(NSError * _Nullable error) {
                                [MBManager showBriefAlert:ASLocalizedString(@"分享失败")clickHidden:NO clickBlock:nil];
                            }];
                        }else{
                            //                            UMSocialLogInfo(@"response data is %@",data);
                            [MBManager showBriefAlert:ASLocalizedString(@"分享失败")clickHidden:NO clickBlock:nil];
                        }
                    }
                }];
            }];
            [signal subscribeError:^(NSError * _Nullable error) {
                [MBManager showBriefAlert:ASLocalizedString(@"获取分享信息失败")clickHidden:NO clickBlock:nil];
            }];
        }];
    } merchantsBlock:^{
        // BDLog(ASLocalizedString(@"付费或查看详情按钮"));
        if (model.free || (model.free == NO && model.isPurchase == YES)) {
            BDHomeDetailViewController *detailViewController = [[BDHomeDetailViewController alloc] init];
            detailViewController.hidesBottomBarWhenPushed = YES;
            if (model.haveShopInfo) {
                detailViewController.homeModel = model;
            }else{
                detailViewController.homeModel = model.repost;
            }
            [self.navigationController pushViewController:detailViewController animated:YES];
        }else{
            BOOL isControl = [[[NSUserDefaults standardUserDefaults] objectForKey:@"versionControl"] boolValue];
            BDUserModel *currentUser = [BDUserModel getCurrentUser];
            
            if (isControl == YES || currentUser.is_auth == NO) {
                [[UIApplication sharedApplication].keyWindow alertWithTitle:ASLocalizedString(@"提示")message:ASLocalizedString(@"购买会员可以查看所有加密帖子，是否前往购买？")type:AlertTypeAlert cancleTitle:ASLocalizedString(@"取消")otherTitle:@[ASLocalizedString(@"好的")] clickBlock:^(NSInteger index) {
                    if (index == 1) {
                        BDVIPViewController *vipVC = [[BDVIPViewController alloc] init];
                        [self.navigationController pushViewController:vipVC animated:YES];
                    }
                }];
            }else{
                BDVipPayView *payView = [BDVipPayView showWithProductId:model.my_id type:BDPayTypePost title:ASLocalizedString(@"购买主题")product:[NSString stringWithFormat:ASLocalizedString(@"%@的主题"), model.repost == nil ? model.user.nickname : model.repost.user.nickname] price:[NSString stringWithFormat:ASLocalizedString(@"%@ 元"), @(model.price)] addressArray:nil];
                __weak AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
                app.payResultBlock = ^(int state) {
                    // BDLog(ASLocalizedString(@"支付会调用这个回调回到这个页面"));
                    app.payResultBlock = nil;
                    [payView hidden];
                    if (state == 1) {
                        [MBManager showBriefAlert:ASLocalizedString(@"支付成功")clickHidden:NO clickBlock:nil];
                        model.purchase = @[@""];
                        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                    }else if (state == 2) {
                        [MBManager showBriefAlert:ASLocalizedString(@"支付失败")clickHidden:YES clickBlock:nil];
                    }else if (state == 3) {
                        [MBManager showBriefAlert:ASLocalizedString(@"支付取消")clickHidden:YES clickBlock:nil];
                    }
                };
            }
        }
    } imageClickBlock:^(NSInteger index, NSArray *imagesArray, UIView *clickView) {
        showImagesArray = imagesArray;
        PBViewController *pbViewController = [PBViewController new];
        pbViewController.pb_dataSource = self;
        pbViewController.pb_delegate = self;
        pbViewController.pb_startPage = index;
        curClickView = clickView;
        [self presentViewController:pbViewController animated:YES completion:nil];
    }];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}

#pragma mark ------------------------PBViewController代理---------------------------
- (NSInteger)numberOfPagesInViewController:(PBViewController *)viewController {
    return showImagesArray.count;
}

- (void)viewController:(PBViewController *)viewController presentImageView:(UIImageView *)imageView forPageAtIndex:(NSInteger)index progressHandler:(void (^)(NSInteger, NSInteger))progressHandler {
    
    UIImage *placeholder = [UIImage imageNamed:@"business_pic"];
    [imageView sd_setImageWithURL:[NSURL URLWithString:showImagesArray[index]]
                 placeholderImage:placeholder
                          options:0
                         progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
                             
                         } completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                             
                         }];
}

- (UIView *)thumbViewForPageAtIndex:(NSInteger)index {
    return curClickView;
}

- (void)viewController:(PBViewController *)viewController didSingleTapedPageAtIndex:(NSInteger)index presentedImage:(UIImage *)presentedImage {
    [self dismissViewControllerAnimated:YES completion:nil];
}


- (UITableView *)tableView{
    if (!_tableView) {
        self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, kBDTopHeight, kBDScreenWidth, kBDScreenHeight - kBDTopHeight) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [[UIView alloc] init];
        [_tableView registerClass:[BDHomeTableViewCell class] forCellReuseIdentifier:@"homeResCell"];
        //        _tableView.tableHeaderView = [self customHeaderView];
        _tableView.backgroundColor = [UIColor clearColor];
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

- (NSMutableArray *)datasource{
    if (!_datasource) {
        self.datasource = [NSMutableArray array];
    }
    return _datasource;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
